<template>
  <div class="agent-apply-page">
    <Header />
    <div class="banner">
      <div class="banner-content">
        <h1>申请成为经纪人</h1>
        <p>加入我们的专业团队，开启您的房产经纪人职业生涯</p>
      </div>
    </div>
    
    <div class="container">
      <div v-if="!isLoggedIn" class="login-required">
        <div class="login-message">
          <svg-icon name="warning" />
          <h3>请先登录再提交申请</h3>
          <p>成为经纪人需要您先登录账号</p>
          <el-button type="primary" @click="goToLogin">立即登录</el-button>
        </div>
      </div>
      
      <div v-else class="agent-apply-container">
        <div class="section-title">
          <h2>填写申请信息</h2>
          <p>请填写以下信息，我们将尽快审核您的申请</p>
        </div>
        
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="agent-apply-form">
          <el-alert
            title="经纪人申请将写入经纪人表，状态设置为待审核，管理员审核通过后可成为正式经纪人"
            type="info"
            show-icon
            style="margin-bottom: 20px"
          />
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入真实姓名" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="form.idCard" placeholder="请输入身份证号" />
          </el-form-item>
          <el-form-item label="从业年限" prop="experience">
            <el-input v-model="form.experience" placeholder="如：3年" />
          </el-form-item>
          <el-form-item label="所属公司" prop="company">
            <el-input v-model="form.company" placeholder="请输入所属公司名称" />
          </el-form-item>
          <el-form-item label="执业证书号" prop="licenseNo">
            <el-input v-model="form.licenseNo" placeholder="请输入执业证书号（如无可留空）" />
          </el-form-item>
          <el-form-item label="个人简介" prop="bio">
            <el-input type="textarea" v-model="form.bio" placeholder="请简单介绍自己的房产销售经验和专业背景" :rows="4" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="onSubmit">提交申请</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="info-section">
        <div class="info-card">
          <div class="icon-wrapper">
            <svg-icon name="house/service/home-2" />
          </div>
          <h3>成为专业经纪人的优势</h3>
          <ul>
            <li>获得丰厚的佣金收入</li>
            <li>灵活的工作时间</li>
            <li>专业的培训支持</li>
            <li>完善的客户资源</li>
            <li>良好的职业发展空间</li>
          </ul>
        </div>
        
        <div class="info-card">
          <div class="icon-wrapper">
            <svg-icon name="house/service/home-3" />
          </div>
          <h3>申请流程</h3>
          <ol>
            <li>提交基本信息</li>
            <li>资料审核（1-3个工作日）</li>
            <li>电话面试</li>
            <li>签署合作协议</li>
            <li>开始您的经纪人之旅</li>
          </ol>
        </div>
      </div>
    </div>
    
    <Footer />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { applyAgent } from '@/api/agent'
import { useUserStore } from '@/stores/user'
import { useLoginStore } from '@/stores/login'
import { useRouter } from 'vue-router'
import Header from '@/views/common/Header.vue'
import Footer from '@/views/common/Footer.vue'

const userStore = useUserStore()
const loginStore = useLoginStore()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

// 检查用户是否已登录
const isLoggedIn = computed(() => userStore.isLoggedIn)

// 表单数据
const form = reactive({
  name: '',
  phone: '',
  idCard: '',
  experience: '',
  bio: '',
  company: '吉居榭房产',
  licenseNo: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  experience: [
    { required: true, message: '请输入从业年限', trigger: 'blur' }
  ],
  company: [
    { required: true, message: '请输入所属公司', trigger: 'blur' }
  ],
  bio: [
    { required: true, message: '请填写个人简介', trigger: 'blur' },
    { max: 500, message: '个人简介不能超过500个字符', trigger: 'blur' }
  ]
}

// 初始化时自动填充已登录用户的信息
onMounted(() => {
  if (isLoggedIn.value) {
    const userInfo = userStore.userInfo
    if (userInfo) {
      // 预填充手机号
      if (userInfo.phone || userInfo.phoneNumber) {
        form.phone = userInfo.phone || userInfo.phoneNumber
      }
      // 如果用户已设置真实姓名，也预填充
      if (userInfo.realName) {
        form.name = userInfo.realName
      } else if (userInfo.nickName) {
        form.name = userInfo.nickName
      }
    }
  } else {
    // 如果用户未登录，显示提示并询问是否前往登录
    ElMessageBox.confirm('申请成为经纪人需要先登录账号，是否前往登录？', '提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 用户点击确认，跳转到登录页
      loginStore.showLogin()
    }).catch(() => {
      // 用户取消，留在当前页面
    })
  }
})

// 前往登录页面
const goToLogin = () => {
  loginStore.showLogin()
}

// 提交申请
const onSubmit = () => {
  // 再次检查登录状态
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再提交申请')
    goToLogin()
    return
  }

  formRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      // 构建请求数据对象，确保字段名与后端预期一致
      const requestData = {
        realName: form.name,
        phone: form.phone,
        idCard: form.idCard,
        workYears: parseInt(form.experience) || 0,
        introduction: form.bio,
        company: form.company || '吉居榭房产',
        licenseNo: form.licenseNo || `TMP-${Date.now()}`,
        // 状态初始为待审核(0)
        status: '0'
      }
      
      console.log('提交经纪人申请数据:', requestData)
      
      const res = await applyAgent(requestData)
      console.log('申请响应结果:', res)
      
      if (res.code === 200) {
        ElMessage.success({
          message: '申请已提交，我们将尽快审核您的申请',
          duration: 5000
        })
        // 重置表单
        resetForm()
        // 延迟返回首页
        setTimeout(() => {
          router.push('/')
        }, 2000)
      } else {
        ElMessage.error(res.msg || '申请失败，请稍后重试')
      }
    } catch (e) {
      console.error('申请失败详情:', e)
      
      // 处理不同类型的错误
      if (e.response && e.response.status === 401) {
        ElMessage.error('登录信息已过期，请重新登录')
        goToLogin()
      } else if (e.response && e.response.status === 403) {
        ElMessage.error('您没有申请经纪人的权限')
      } else {
        ElMessage.error(e.message || '申请失败，请稍后重试')
      }
    } finally {
      loading.value = false
    }
  })
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<style lang="scss" scoped>
.agent-apply-page {
  max-width: 1920px;
  margin: 0 auto;
}

.banner {
  height: 280px;
  background: linear-gradient(rgba(47, 59, 89, 0.85), rgba(47, 59, 89, 0.85)), url('@/assets/images/agent-banner.jpg');
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  
  .banner-content {
    text-align: center;
    max-width: 800px;
    padding: 0 20px;
    
    h1 {
      font-size: 42px;
      margin-bottom: 16px;
      font-weight: 600;
    }
    
    p {
      font-size: 18px;
      opacity: 0.9;
    }
  }
}

.container {
  display: flex;
  padding: 60px 60px;
  gap: 40px;
  
  @media (max-width: 1200px) {
    flex-direction: column;
  }
}

.login-required {
  flex: 1;
  background: #fff;
  padding: 60px 40px;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0,0,0,0.08);
  display: flex;
  align-items: center;
  justify-content: center;
  
  .login-message {
    text-align: center;
    max-width: 400px;
    
    svg {
      width: 64px;
      height: 64px;
      color: #ff9800;
      margin-bottom: 20px;
    }
    
    h3 {
      font-size: 24px;
      color: #333;
      margin-bottom: 12px;
    }
    
    p {
      color: #666;
      margin-bottom: 20px;
    }
    
    .el-button {
      width: 180px;
    }
  }
}

.agent-apply-container {
  flex: 1;
  background: #fff;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0,0,0,0.08);
}

.section-title {
  margin-bottom: 32px;
  text-align: center;
  
  h2 {
    font-size: 28px;
    color: #4a60a1;
    margin-bottom: 12px;
  }
  
  p {
    color: #666;
    font-size: 16px;
  }
}

.agent-apply-form {
  max-width: 600px;
  margin: 0 auto;
  
  :deep(.el-button) {
    background: linear-gradient(90deg, #4A60A1, #6A80C1);
    border: none;
    
    &:hover {
      background: linear-gradient(90deg, #6A80C1, #4A60A1);
    }
  }
}

.info-section {
  width: 380px;
  display: flex;
  flex-direction: column;
  gap: 30px;
  
  @media (max-width: 1200px) {
    width: 100%;
    flex-direction: row;
    
    .info-card {
      flex: 1;
    }
  }
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.info-card {
  background: #f9fafc;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  
  .icon-wrapper {
    width: 60px;
    height: 60px;
    background: #4A60A1;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    
    svg {
      width: 30px;
      height: 30px;
      color: #fff;
    }
  }
  
  h3 {
    font-size: 20px;
    color: #2F3B59;
    margin-bottom: 16px;
  }
  
  ul, ol {
    padding-left: 20px;
    margin: 0;
    
    li {
      margin-bottom: 8px;
      color: #555;
      line-height: 1.6;
    }
  }
}

:deep(.el-form-item__label) {
  color: #4a60a1;
  font-weight: 500;
}

:deep(.el-input__inner) {
  border-radius: 6px;
  
  &:focus {
    border-color: #4a60a1;
  }
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
  
  &:focus {
    border-color: #4a60a1;
  }
}
</style> 